package cn.edu.zafu.bigdata.YinMingyan.chapter11;

import java.io.*;
import java.net.*;

// UDP时间服务器
public class UDPTimeServer {
    public static void main(String[] args) {
        int port = 6789; // 服务器监听的端口号
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("UDP Time server running on port " + port);

            while (true) {
                // 创建一个字节数组用于接收数据
                byte[] receiveData = new byte[1024];
                // 创建一个DatagramPacket用于接收客户端请求
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收客户端请求
                socket.receive(receivePacket);
                String request = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("UDP Received request: " + request);

                // 获取服务器当前时间
                String currentTime = new java.util.Date().toString();

                // 发送时间响应给客户端
                byte[] sendData = currentTime.getBytes();
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                socket.send(sendPacket);
                System.out.println("UDP Sent time: " + currentTime);
            }
        } catch (IOException e) {
            System.err.println("UDP Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}